import random

from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from verfications import contents
from meiduo_mall.libs.yuntongxun.sms import CCP
import logging

logger = logging.getLogger("django")


class SMSCodeView(APIView):
    def get(self, request, mobile):
        """
        短信验证码获取：
        1. 随机生成六位数字作为短信验证码内容
        2. 在redis中存储短信验证码真实内容
        3. 使用云通讯给mobile发送验证码
        4. 返回应答，短信发送成功
        """
        # 判断60s之内是否给`mobile`发过短信
        redis_conn = get_redis_connection('verify_codes')        #快速获取数据库的连接

        send_flag = redis_conn.get('send_flag_%s' % mobile)  # None

        if send_flag:
            return Response({'message': '发送短信过于频繁'}, status=status.HTTP_400_BAD_REQUEST)

        # 1. 随机生成六位数字作为短信验证码内容
        sms_code = "%06d" % random.randint(0, 999999)
        logger.info("短信验证码为：%s" % sms_code)

        # 2. 在redis中存储短信验证码真实内容

        # redis_conn = get_redis_connection("<key>","<value>", "<expires>")
        # redis_conn.setex("<key>", "<expires>","<value>")

        # 创建管道对象：
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, contents.SMS_CODES_REDIS_EXPIRES, sms_code)  #保存验证码
        pl.setex('send_flag_%s' % mobile, contents.SEND_SMS_INTERVAL, 1)    #保存短信发送的一个标记

        # 一次性执行管道中的所有命令
        pl.execute()


        #使用celery异步发送短信验证码
        from celery_tasks.sms.tasks import send_sms_code

        expires = contents.SMS_CODES_REDIS_EXPIRES // 60
        send_sms_code.delay(mobile, sms_code, expires)

        return Response({"message": "OK"})





